import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserInfo } from '@/api/userApi'
interface statusType {
  token: string
  userInfo: object
  mobile: string
}

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    mobile: ''
  } as statusType
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state: statusType) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state: statusType, token: string) => {
    state.token = token
  },
  SET_MOBILE: (state: statusType, mobile: string) => {
    state.mobile = mobile
  },
  SET_USERINFO: (state: statusType, userInfo: object) => {
    state.userInfo = userInfo
  }
}

const actions = {
  /** user login*/
  login({ commit }, params) {
    const { code } = params
    return new Promise((resolve, reject) => {
      login({ code: code, appid: import.meta.env.VITE_APP_APPID })
        .then((response) => {
          const { data } = response
          setToken(data.access_token)
          commit('SET_TOKEN', data.access_token)
          resolve(data.access_token)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /** get user info*/
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getUserInfo()
        .then((response) => {
          const { data } = response
          commit('SET_USERINFO', data)
          commit('SET_MOBILE', data.mobile)
          resolve(data)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  loginOut({ commit }) {
    return new Promise<void>((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
